<template>
  <!-- 查询表单 -->
  <el-form
    ref="formSearchRef"
    label-width="100px"
    :inline="true"
    :model="formSearch"
    class="data-grid-search-form"
  >
    <el-row>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item :label="t('log.category')">
          <el-input v-model="formSearch.category" clearable> </el-input>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item lnline-message :label="t('log.logLevel')">
          <el-select v-model="formSearch.logLevel" clearable>
            <el-option :label="t('log.logLevelInfo')" value="0"></el-option>
            <el-option :label="t('log.logLevelWarn')" value="1"></el-option>
            <el-option :label="t('log.logLevelError')" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item :label="t('log.logAction')">
          <el-input v-model="formSearch.logAction" clearable> </el-input>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24" v-if="searchInputExpland">
        <el-form-item :label="t('log.logInfo')">
          <el-input v-model="formSearch.logInfo" clearable> </el-input>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24" v-if="searchInputExpland">
        <el-form-item :label="t('log.createAccountName')">
          <el-input v-model="formSearch.createAccountName" clearable>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24" v-if="searchInputExpland">
        <el-form-item label="IP">
          <el-input v-model="formSearch.ipAddress" clearable> </el-input>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24" v-if="searchInputExpland">
        <el-form-item :label="t('log.hostId')">
          <el-input v-model="formSearch.hostId" clearable> </el-input>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24" v-if="searchInputExpland">
        <el-form-item :label="t('log.businessKey')">
          <el-input v-model="formSearch.businessKey" clearable> </el-input>
        </el-form-item>
      </el-col>

      <el-col :lg="6" :md="8" :sm="12" :xs="24" v-if="searchInputExpland">
        <el-form-item :label="t('common.startDate')">
          <el-date-picker
            v-model="formSearch.createTimeBegin"
            type="datetime"
            :shortcuts="shortcuts"
            clearable
            class="fix-el-date-picker-width"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24" v-if="searchInputExpland">
        <el-form-item :label="t('common.to')">
          <el-date-picker
            v-model="formSearch.createTimeEnd"
            type="datetime"
            :shortcuts="shortcuts"
            clearable
            class="fix-el-date-picker-width"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :lg="6" :md="8" :sm="12" :xs="24">
        <el-form-item style="float: right">
          <el-button :icon="Search" type="primary" @click="handleSearch">{{
            t("common.searchButton")
          }}</el-button>
          <el-button
            :icon="RefreshLeft"
            @click="formSearchRef.value.resetFields()"
            >{{ t("common.resetButton") }}</el-button
          >
          <search-input-expland
            @on-expland-change="(v:boolean)=>{ searchInputExpland=v}"
          ></search-input-expland>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>

  <data-grid
    ref="dataGridRef"
    id="admin-log-grid"
    row-key="logId"
    defaultSort="descending"
    defaultSortBy="createTime"
    :request="handleLoadGrid"
    :columns="state.columns"
    :buttons="state.buttons"
  >
    <!-- 自定义模板，会替换控件中的 buttonSlot id：button 仅在当前作用域有效 -->
    <template #button-primary="button">
      <!-- <el-button size="mini" :icon="Download">导出日志</el-button> -->
    </template>

    <!-- 自定义模板，会替换控件中的 tdSlot，模板 account 仅在当前作用域有效 -->
    <template #logInfo="slotProps">
      <el-link
        type="primary"
        @click="handleView(slotProps.row)"
        style="font-weight: normal"
        >{{ formatTitle(slotProps.row.logInfo) }}</el-link
      >
    </template>

    <template #category="slotProps">
      <el-tag size="small" type="info"> {{ slotProps.row.category }}</el-tag>
    </template>

    <template #logLevel="slotProps">
      <el-tag size="small" v-if="slotProps.row.logLevel == 0">
        {{ t("log.logLevelInfo") }}</el-tag
      >
      <el-tag size="small" v-if="slotProps.row.logLevel == 1" type="warning">
        {{ t("log.logLevelWarn") }}</el-tag
      >
      <el-tag size="small" v-if="slotProps.row.logLevel == 2" type="danger">
        {{ t("log.logLevelError") }}</el-tag
      >
    </template>

    <template #logAction="slotProps">
      <el-tag size="small" type="info"> {{ slotProps.row.logAction }}</el-tag>
    </template>
  </data-grid>

  <view-form ref="viewFormRef"></view-form>
</template>
<script setup lang="ts">
import { reactive, ref, toRefs } from "vue";
import DataGrid from "@/components/DataGrid.vue";
import SearchInputExpland from "../../../components/SearchInputExpland.vue";
import ViewForm from "./view.vue";
import { Search, RefreshLeft } from "@element-plus/icons-vue";
import utils from "../../../utils/utils";
import moment from "moment";
import apiLog from "../api/log";
import { useI18n } from "vue-i18n";
const { t } = useI18n({ useScope: "global" });
// 变量必须和属性 ref 的值相同
const formSearchRef = ref();
const dataGridRef = ref();
const viewFormRef = ref();
// 展开收缩
const searchInputExpland = ref(false);

// 查询区域表单数据
const formSearch = reactive({
  logId: "",
  category: "",
  logAction: "",
  logLevel: "",
  logInfo: "",
  businessKey: "",
  hostId: "",
  ipAddress: "",
  createAccountName: "",
  // 前端控件使用
  createTimeBegin: <Date>(<any>null),
  createTimeEnd: <Date>(<any>null),
  // 提交后台使用
  createTimeBeginString: "",
  createTimeEndString: "",
});

const shortcuts = [
  {
    text: t("common.aWeekAgo"),
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      formSearch.createTimeBegin = start;
      formSearch.createTimeEnd = end;
      // return [start, end];
    },
  },
  {
    text: t("common.lastMonth"),
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      formSearch.createTimeBegin = start;
      formSearch.createTimeEnd = end;
      // return [start, end];
    },
  },
  {
    text: t("common.last3Months"),
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      formSearch.createTimeBegin = start;
      formSearch.createTimeEnd = end;
      // return [start, end];
    },
  },
];

const state = reactive({
  // 表格列配置，大部分属性跟el-table-column配置一样
  columns: [
    {
      title: () => t("log.category"),
      field: "category",
      sortable: true,
      resizable: true,
      tdSlot: "category",
      width: 120,
    },
    {
      title: () => t("log.logLevel"),
      field: "logLevel",
      sortable: true,
      resizable: true,
      tdSlot: "logLevel",
      width: 100,
    },
    {
      title: () => t("log.logAction"),
      field: "logAction",
      sortable: true,
      resizable: "true",
      tdSlot: "logAction",
      width: 150,
    },
    {
      title: () => t("log.logInfo"),
      field: "logInfo",
      resizable: "true",
      className: "test-ellipsis",
      tdSlot: "logInfo",
    },
    {
      title: () => t("log.createAccountName"),
      field: "createAccountName",
      sortable: true,
      resizable: true,
      width: 150,
    },
    {
      title: "IP",
      field: "ipAddress",
      sortable: true,
      resizable: true,
      width: 150,
    },
    {
      title: () => t("log.hostId"),
      field: "hostId",
      sortable: true,
      resizable: true,
      hidden: true,
    },
    {
      title: () => t("log.businessKey"),
      field: "businessKey",
      sortable: true,
      resizable: true,
      hidden: true,
    },
    {
      title: () => t("log.createTime"),
      field: "createTime",
      sortable: true,
      resizable: true,
      width: 180,
    },
  ],
  buttons: [
    {
      type: "primary",
      buttonSlot: "button-primary",
    },
  ],
  row: null,
});

// 加载数据
const handleLoadGrid = async (params: any) => {
  // 后台处理不了默认的时间格式，需要转换一下
  if (formSearch.createTimeBegin != null) {
    formSearch.createTimeBeginString = moment(
      formSearch.createTimeBegin
    ).format("YYYY-MM-DD HH:mm:ss");
  }
  if (formSearch.createTimeEnd != null) {
    formSearch.createTimeEndString = moment(formSearch.createTimeEnd).format(
      "YYYY-MM-DD HH:mm:ss"
    );
  }

  let query = utils.serializeArray(formSearch);
  params.query = JSON.stringify(query);
  let data = { rows: [], total: 0 };
  await apiLog
    .queryLogListing(params)
    .then((respons: any) => {
      if (respons != undefined) {
        data = respons.data;
      }
    })
    .catch((err: any) => {
      utils.errorNotification(t("common.submitException"), err);
    });

  // 返回数据给表格组件
  return data;
};

const formatTitle = (cellValue: string) => {
  if (cellValue != undefined) {
    return cellValue.length > 64
      ? cellValue.substring(0, 64) + "..."
      : cellValue;
  }
  return cellValue;
};

// 打开详情页
const handleView = (row: any) => {
  viewFormRef.value.show(row);
};

// 刷新表格
const handleSearch = () => {
  dataGridRef.value.loadGridData();
};
</script>
